# -*- coding: utf-8 -*-
"""
Python 2.7 和 Python 3.x 兼容性模块
处理不同Python版本之间的差异
"""
from __future__ import print_function

import sys
import os

# Python版本检测
PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3
PY_VERSION = sys.version_info[:2]

# 兼容性导入
if PY3:
    import urllib.parse as urlparse
    from urllib.request import urlopen
    from urllib.error import URLError
    string_types = (str,)
    integer_types = (int,)
    text_type = str
    binary_type = bytes
    
    def iteritems(d):
        return d.items()
    
    def itervalues(d):
        return d.values()
    
    def iterkeys(d):
        return d.keys()
        
else:  # Python 2
    import urlparse
    from urllib2 import urlopen, URLError
    string_types = (basestring,)
    integer_types = (int, long)
    text_type = unicode
    binary_type = str
    
    def iteritems(d):
        return d.iteritems()
    
    def itervalues(d):
        return d.itervalues()
    
    def iterkeys(d):
        return d.iterkeys()

# 兼容的print函数
if PY2:
    def print_function(*args, **kwargs):
        """Python 2兼容的print函数"""
        sep = kwargs.get('sep', ' ')
        end = kwargs.get('end', '\n')
        file_obj = kwargs.get('file', sys.stdout)
        
        output = sep.join(str(arg) for arg in args) + end
        file_obj.write(output)
        file_obj.flush()
else:
    print_function = print

# 字符串格式化兼容函数
def format_string(template, *args, **kwargs):
    """
    兼容的字符串格式化函数
    支持Python 2.7和3.x的格式化语法
    """
    if PY3:
        # Python 3可以直接使用format
        return template.format(*args, **kwargs)
    else:
        # Python 2需要特殊处理
        try:
            return template.format(*args, **kwargs)
        except (KeyError, ValueError):
            # 如果format失败，尝试使用%格式化
            if args and not kwargs:
                return template % args
            elif kwargs and not args:
                return template % kwargs
            else:
                return template

# 文件操作兼容
def open_file(filename, mode='r', encoding=None):
    """兼容的文件打开函数"""
    if PY3:
        return open(filename, mode, encoding=encoding or 'utf-8')
    else:
        if 'b' in mode:
            return open(filename, mode)
        else:
            import codecs
            return codecs.open(filename, mode, encoding=encoding or 'utf-8')

# 异常处理兼容
def get_exception_message(e):
    """获取异常消息的兼容函数"""
    if PY3:
        return str(e)
    else:
        return unicode(e) if hasattr(e, 'message') else str(e)

# 输入函数兼容
if PY3:
    input_function = input
else:
    input_function = raw_input

# 范围函数兼容
if PY3:
    range_function = range
else:
    range_function = xrange

# 字典键值兼容
def dict_keys(d):
    """获取字典键的兼容函数"""
    if PY3:
        return list(d.keys())
    else:
        return d.keys()

def dict_values(d):
    """获取字典值的兼容函数"""
    if PY3:
        return list(d.values())
    else:
        return d.values()

def dict_items(d):
    """获取字典项的兼容函数"""
    if PY3:
        return list(d.items())
    else:
        return d.items()

# 类型检查兼容
def is_string(obj):
    """检查是否为字符串类型"""
    return isinstance(obj, string_types)

def is_integer(obj):
    """检查是否为整数类型"""
    return isinstance(obj, integer_types)

# 编码解码兼容
def ensure_str(s, encoding='utf-8'):
    """确保返回字符串类型"""
    if PY3:
        if isinstance(s, bytes):
            return s.decode(encoding)
        return str(s)
    else:
        if isinstance(s, unicode):
            return s.encode(encoding)
        return str(s)

def ensure_bytes(s, encoding='utf-8'):
    """确保返回字节类型"""
    if PY3:
        if isinstance(s, str):
            return s.encode(encoding)
        return bytes(s)
    else:
        if isinstance(s, unicode):
            return s.encode(encoding)
        return str(s)

# 模块导入兼容
def import_module(module_name):
    """兼容的模块导入函数"""
    try:
        if PY3:
            import importlib
            return importlib.import_module(module_name)
        else:
            __import__(module_name)
            return sys.modules[module_name]
    except ImportError:
        return None

# 时间兼容
def get_timestamp():
    """获取时间戳的兼容函数"""
    import time
    if PY3:
        return time.time()
    else:
        return long(time.time())

# JSON兼容
def json_dumps(obj, **kwargs):
    """JSON序列化兼容函数"""
    import json
    if PY2:
        kwargs.setdefault('ensure_ascii', False)
    return json.dumps(obj, **kwargs)

def json_loads(s):
    """JSON反序列化兼容函数"""
    import json
    return json.loads(s)

# 进程兼容
def subprocess_run(cmd, **kwargs):
    """subprocess运行兼容函数"""
    import subprocess
    
    if PY3 and hasattr(subprocess, 'run'):
        return subprocess.run(cmd, **kwargs)
    else:
        # Python 2兼容实现
        shell = kwargs.get('shell', False)
        capture_output = kwargs.get('capture_output', False)
        text = kwargs.get('text', False)
        
        if capture_output:
            stdout = subprocess.PIPE
            stderr = subprocess.PIPE
        else:
            stdout = kwargs.get('stdout', None)
            stderr = kwargs.get('stderr', None)
        
        try:
            proc = subprocess.Popen(
                cmd, 
                shell=shell, 
                stdout=stdout, 
                stderr=stderr,
                universal_newlines=text
            )
            stdout_data, stderr_data = proc.communicate()
            
            # 创建类似subprocess.CompletedProcess的对象
            class CompletedProcess(object):
                def __init__(self, args, returncode, stdout=None, stderr=None):
                    self.args = args
                    self.returncode = returncode
                    self.stdout = stdout
                    self.stderr = stderr
            
            return CompletedProcess(cmd, proc.returncode, stdout_data, stderr_data)
        except Exception as e:
            class CompletedProcess(object):
                def __init__(self, args, returncode, stdout=None, stderr=None):
                    self.args = args
                    self.returncode = returncode
                    self.stdout = stdout
                    self.stderr = stderr
            
            return CompletedProcess(cmd, 1, None, str(e))

# 路径兼容
def path_join(*args):
    """路径连接兼容函数"""
    return os.path.join(*args)

def path_exists(path):
    """路径存在检查兼容函数"""
    return os.path.exists(path)

# 版本信息
def get_python_version():
    """获取Python版本信息"""
    return {
        'version': sys.version,
        'version_info': sys.version_info,
        'major': sys.version_info[0],
        'minor': sys.version_info[1],
        'micro': sys.version_info[2],
        'is_py2': PY2,
        'is_py3': PY3
    }

# 兼容性检查
def check_compatibility():
    """检查当前Python版本的兼容性"""
    version_info = get_python_version()
    
    if version_info['major'] == 2:
        if version_info['minor'] < 7:
            return False, "需要Python 2.7或更高版本"
    elif version_info['major'] == 3:
        if version_info['minor'] < 0:
            return False, "需要Python 3.0或更高版本"
    else:
        return False, "不支持的Python版本"
    
    return True, "Python版本兼容"

# 导出所有兼容性函数
__all__ = [
    'PY2', 'PY3', 'PY_VERSION',
    'print_function', 'format_string', 'open_file',
    'get_exception_message', 'input_function', 'range_function',
    'dict_keys', 'dict_values', 'dict_items',
    'is_string', 'is_integer',
    'ensure_str', 'ensure_bytes',
    'import_module', 'get_timestamp',
    'json_dumps', 'json_loads',
    'subprocess_run', 'path_join', 'path_exists',
    'get_python_version', 'check_compatibility',
    'iteritems', 'itervalues', 'iterkeys',
    'string_types', 'integer_types', 'text_type', 'binary_type'
]